import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import { loginApi } from '@/api/index';
import { getUserInfoApi } from '@/api/person';
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: '',
    user: {},
    time: 0
  },
  mutations: {
    setUser(state, data) {
      state.user = data.user;
      state.token = data.token;
      state.time = +new Date();
    },
    removeUser(state) {
      state.user = {};
      state.token = '';
    },
    resetUser(state, data) {
      state.user = data
    }
  },
  actions: {
    async login({ commit }, data) {
      const res = await loginApi(data);
      if (res.status === 0) {
        commit('setUser', res.data);
      }
      return res;
    },
    async ReSetUser({ commit,state }) {
      if(state.token){
        const res = await getUserInfoApi();
        commit('resetUser', res.data);
      }
    }
  },
  plugins: [
    createPersistedState({
      key: 'OLAYUN'
    })
  ]
});
